<template>
  <div class="personal-center">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" size="small" @click="showEditDialog">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
            </div>
          </template>
          
          <div class="profile-info">
            <div class="avatar-section">
              <el-avatar :size="80" :src="userInfo.avatar">
                {{ userInfo.username?.charAt(0).toUpperCase() }}
              </el-avatar>
              <h3>{{ userInfo.first_name }} {{ userInfo.last_name || userInfo.username }}</h3>
              <el-tag :type="getRoleType(userInfo.role)">{{ getRoleText(userInfo.role) }}</el-tag>
            </div>
            
            <div class="info-list">
              <div class="info-item">
                <span class="label">用户名:</span>
                <span class="value">{{ userInfo.username }}</span>
              </div>
              <div class="info-item">
                <span class="label">邮箱:</span>
                <span class="value">{{ userInfo.email || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机号:</span>
                <span class="value">{{ userInfo.phone || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">注册时间:</span>
                <span class="value">{{ formatDate(userInfo.date_joined) }}</span>
              </div>
              <div class="info-item">
                <span class="label">最后登录:</span>
                <span class="value">{{ formatDate(userInfo.last_login) }}</span>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 快捷操作 -->
        <el-card class="quick-actions" style="margin-top: 20px;">
          <template #header>
            <span>快捷操作</span>
          </template>

          <div class="action-buttons">
            <el-button type="primary" @click="showPasswordDialog">
              <el-icon><Lock /></el-icon>
              修改密码
            </el-button>
            <el-button type="success" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
            <el-button type="warning" @click="showPreferencesDialog">
              <el-icon><Setting /></el-icon>
              个人偏好
            </el-button>
          </div>
        </el-card>

        <!-- 安全设置 -->
        <el-card class="security-settings" style="margin-top: 20px;">
          <template #header>
            <span>安全设置</span>
          </template>

          <div class="security-info">
            <div class="security-item">
              <div class="security-label">
                <el-icon><User /></el-icon>
                <span>账户安全</span>
              </div>
              <div class="security-status">
                <el-tag :type="userInfo.is_active ? 'success' : 'danger'">
                  {{ userInfo.is_active ? '正常' : '已禁用' }}
                </el-tag>
              </div>
            </div>

            <div class="security-item">
              <div class="security-label">
                <el-icon><Key /></el-icon>
                <span>密码强度</span>
              </div>
              <div class="security-status">
                <el-tag type="warning">中等</el-tag>
              </div>
            </div>

            <div class="security-item">
              <div class="security-label">
                <el-icon><Clock /></el-icon>
                <span>会话状态</span>
              </div>
              <div class="security-status">
                <el-tag type="success">在线</el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧统计和历史 -->
      <el-col :span="16">
        <!-- 统计信息 -->
        <el-card class="statistics-card">
          <template #header>
            <span>个人统计</span>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ statistics.total_logins || 0 }}</div>
                <div class="stat-label">总登录次数</div>
              </div>
            </el-col>
            <el-col :span="6" v-if="statistics.supervised_students !== undefined">
              <div class="stat-item">
                <div class="stat-number">{{ statistics.supervised_students }}</div>
                <div class="stat-label">指导学生</div>
              </div>
            </el-col>
            <el-col :span="6" v-if="statistics.student_id">
              <div class="stat-item">
                <div class="stat-number">{{ statistics.student_id }}</div>
                <div class="stat-label">学号</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ userInfo.is_active ? '正常' : '禁用' }}</div>
                <div class="stat-label">账户状态</div>
              </div>
            </el-col>
          </el-row>
          
          <!-- 学生特有信息 -->
          <div v-if="userInfo.role === 'student' && statistics.grade" class="student-info">
            <el-divider />
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">所属年级:</span>
                  <span class="value">{{ statistics.grade }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">学籍状态:</span>
                  <el-tag :type="getStatusType(statistics.status)">{{ statistics.status }}</el-tag>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">就业状态:</span>
                  <el-tag :type="getEmploymentType(statistics.employment_status)">{{ statistics.employment_status }}</el-tag>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
        
        <!-- 登录历史 -->
        <el-card class="login-history" style="margin-top: 20px;">
          <template #header>
            <span>最近登录记录</span>
          </template>
          
          <el-table :data="loginHistory" style="width: 100%">
            <el-table-column prop="login_time" label="登录时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.login_time) }}
              </template>
            </el-table-column>
            <el-table-column prop="ip_address" label="IP地址" width="140" />
            <el-table-column prop="user_agent" label="设备信息" show-overflow-tooltip />
            <el-table-column prop="is_success" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.is_success ? 'success' : 'danger'">
                  {{ row.is_success ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 编辑个人信息对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑个人信息" width="600px">
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="姓" prop="first_name">
              <el-input v-model="editForm.first_name" placeholder="请输入姓" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名" prop="last_name">
              <el-input v-model="editForm.last_name" placeholder="请输入名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateProfile" :loading="updating">
          保存
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="500px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="当前密码" prop="old_password">
          <el-input v-model="passwordForm.old_password" type="password" placeholder="请输入当前密码" />
        </el-form-item>
        
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="passwordForm.new_password" type="password" placeholder="请输入新密码" />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input v-model="passwordForm.confirm_password" type="password" placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
          修改密码
        </el-button>
      </template>
    </el-dialog>

    <!-- 个人偏好设置对话框 -->
    <el-dialog v-model="preferencesDialogVisible" title="个人偏好设置" width="600px">
      <el-form ref="preferencesFormRef" :model="preferencesForm" label-width="120px">
        <el-form-item label="界面主题">
          <el-radio-group v-model="preferencesForm.theme">
            <el-radio label="light">浅色主题</el-radio>
            <el-radio label="dark">深色主题</el-radio>
            <el-radio label="auto">跟随系统</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="语言设置">
          <el-select v-model="preferencesForm.language" placeholder="选择语言">
            <el-option label="简体中文" value="zh-CN" />
            <el-option label="English" value="en-US" />
          </el-select>
        </el-form-item>

        <el-form-item label="时区设置">
          <el-select v-model="preferencesForm.timezone" placeholder="选择时区">
            <el-option label="北京时间 (UTC+8)" value="Asia/Shanghai" />
            <el-option label="东京时间 (UTC+9)" value="Asia/Tokyo" />
            <el-option label="纽约时间 (UTC-5)" value="America/New_York" />
          </el-select>
        </el-form-item>

        <el-form-item label="邮件通知">
          <el-switch
            v-model="preferencesForm.emailNotifications"
            active-text="开启"
            inactive-text="关闭"
          />
        </el-form-item>

        <el-form-item label="桌面通知">
          <el-switch
            v-model="preferencesForm.desktopNotifications"
            active-text="开启"
            inactive-text="关闭"
          />
        </el-form-item>

        <el-form-item label="自动保存">
          <el-switch
            v-model="preferencesForm.autoSave"
            active-text="开启"
            inactive-text="关闭"
          />
        </el-form-item>

        <el-form-item label="页面大小">
          <el-select v-model="preferencesForm.pageSize" placeholder="选择每页显示数量">
            <el-option label="10 条/页" :value="10" />
            <el-option label="20 条/页" :value="20" />
            <el-option label="50 条/页" :value="50" />
            <el-option label="100 条/页" :value="100" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="preferencesDialogVisible = false">取消</el-button>
        <el-button @click="resetPreferences">重置默认</el-button>
        <el-button type="primary" @click="handleSavePreferences" :loading="savingPreferences">
          保存设置
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, Lock, Refresh, Setting, User, Key, Clock } from '@element-plus/icons-vue'
import { personalCenterApi } from '@/api/profile'

// 响应式数据
const loading = ref(false)
const updating = ref(false)
const changingPassword = ref(false)
const savingPreferences = ref(false)
const editDialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const preferencesDialogVisible = ref(false)

const userInfo = ref<any>({})
const statistics = ref<any>({})
const loginHistory = ref<any[]>([])

// 表单数据
const editForm = reactive({
  first_name: '',
  last_name: '',
  email: '',
  phone: ''
})

const passwordForm = reactive({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

const preferencesForm = reactive({
  theme: 'light',
  language: 'zh-CN',
  timezone: 'Asia/Shanghai',
  emailNotifications: true,
  desktopNotifications: false,
  autoSave: true,
  pageSize: 20
})

// 表单验证规则
const editRules = {
  email: [
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const passwordRules = {
  old_password: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.new_password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const fetchUserProfile = async () => {
  try {
    const response = await personalCenterApi.getProfile()
    // 检查响应结构
    if (response && response.data) {
      userInfo.value = response.data
    } else if (response) {
      userInfo.value = response
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error(`获取用户信息失败: ${error.message || error}`)
    // 设置默认值
    userInfo.value = {
      username: '未知用户',
      role: 'student',
      email: '',
      phone: '',
      is_active: true,
      date_joined: '',
      last_login: ''
    }
  }
}

const fetchStatistics = async () => {
  try {
    const response = await personalCenterApi.getStatistics()
    // 检查响应结构
    if (response && response.data) {
      statistics.value = response.data
    } else if (response) {
      statistics.value = response
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
    // 设置默认值
    statistics.value = {
      total_logins: 0,
      role: '未知',
      is_active: true
    }
  }
}

const fetchLoginHistory = async () => {
  try {
    const response = await personalCenterApi.getLoginHistory()
    // 检查响应结构
    if (response && response.data) {
      loginHistory.value = response.data
    } else if (response) {
      loginHistory.value = response
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    console.error('获取登录历史失败:', error)
    // 设置默认值
    loginHistory.value = []
  }
}

const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchUserProfile(),
      fetchStatistics(),
      fetchLoginHistory()
    ])
    ElMessage.success('数据刷新成功')
  } finally {
    loading.value = false
  }
}

const showEditDialog = () => {
  editForm.first_name = userInfo.value.first_name || ''
  editForm.last_name = userInfo.value.last_name || ''
  editForm.email = userInfo.value.email || ''
  editForm.phone = userInfo.value.phone || ''
  editDialogVisible.value = true
}

const showPasswordDialog = () => {
  passwordForm.old_password = ''
  passwordForm.new_password = ''
  passwordForm.confirm_password = ''
  passwordDialogVisible.value = true
}

const showPreferencesDialog = () => {
  // 从localStorage加载偏好设置
  loadPreferences()
  preferencesDialogVisible.value = true
}

const loadPreferences = () => {
  const savedPreferences = localStorage.getItem('userPreferences')
  if (savedPreferences) {
    try {
      const preferences = JSON.parse(savedPreferences)
      Object.assign(preferencesForm, preferences)
    } catch (error) {
      console.error('加载偏好设置失败:', error)
    }
  }
}

const resetPreferences = () => {
  preferencesForm.theme = 'light'
  preferencesForm.language = 'zh-CN'
  preferencesForm.timezone = 'Asia/Shanghai'
  preferencesForm.emailNotifications = true
  preferencesForm.desktopNotifications = false
  preferencesForm.autoSave = true
  preferencesForm.pageSize = 20
}

const handleUpdateProfile = async () => {
  updating.value = true
  try {
    await personalCenterApi.updateProfile(editForm)
    ElMessage.success('个人信息更新成功')
    editDialogVisible.value = false
    await fetchUserProfile()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '更新失败')
  } finally {
    updating.value = false
  }
}

const handleChangePassword = async () => {
  changingPassword.value = true
  try {
    await personalCenterApi.changePassword(passwordForm)
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '密码修改失败')
  } finally {
    changingPassword.value = false
  }
}

const handleSavePreferences = async () => {
  savingPreferences.value = true
  try {
    // 保存到localStorage
    localStorage.setItem('userPreferences', JSON.stringify(preferencesForm))

    // 应用主题设置
    applyThemeSettings()

    // 这里可以添加保存到服务器的逻辑
    // await personalCenterApi.savePreferences(preferencesForm)

    ElMessage.success('偏好设置保存成功')
    preferencesDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error('偏好设置保存失败')
  } finally {
    savingPreferences.value = false
  }
}

const applyThemeSettings = () => {
  // 应用主题设置
  if (preferencesForm.theme === 'dark') {
    document.documentElement.classList.add('dark')
  } else if (preferencesForm.theme === 'light') {
    document.documentElement.classList.remove('dark')
  } else {
    // 跟随系统
    const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    if (isDark) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
}

// 工具方法
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString()
}

const formatDateTime = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

const getRoleType = (role: string) => {
  const typeMap: any = {
    'admin': 'danger',
    'teacher': 'warning',
    'student': 'primary'
  }
  return typeMap[role] || 'info'
}

const getRoleText = (role: string) => {
  const textMap: any = {
    'admin': '管理员',
    'teacher': '老师',
    'student': '学生'
  }
  return textMap[role] || role
}

const getStatusType = (status: string) => {
  const typeMap: any = {
    '在校': 'success',
    '已毕业': 'primary',
    '休学': 'warning',
    '退学': 'danger'
  }
  return typeMap[status] || 'info'
}

const getEmploymentType = (status: string) => {
  const typeMap: any = {
    '已就业': 'success',
    '未就业': 'warning',
    '自主创业': 'primary',
    '继续深造': 'info'
  }
  return typeMap[status] || 'info'
}

// 生命周期
onMounted(() => {
  refreshData()
  loadPreferences()
  applyThemeSettings()
})
</script>

<style scoped>
.personal-center {
  padding: 20px;
}

.profile-card {
  height: fit-content;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 30px;
}

.avatar-section h3 {
  margin: 15px 0 10px 0;
  color: #303133;
}

.info-list {
  text-align: left;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #909399;
  font-weight: 500;
}

.value {
  color: var(--text-color-primary);
}

.quick-actions .action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.quick-actions .el-button {
  width: 100%;
}

.security-settings .security-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--fill-color-light);
  border-radius: 6px;
  border-left: 4px solid var(--color-primary);
}

.security-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-color-regular);
  font-weight: 500;
}

.security-status {
  display: flex;
  align-items: center;
}

.statistics-card .stat-item {
  text-align: center;
  padding: 20px 0;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: var(--color-primary);
  margin-bottom: 8px;
}

.stat-label {
  color: var(--text-color-secondary);
  font-size: 14px;
}

.student-info .info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 10px;
}

.student-info .label {
  margin-bottom: 8px;
}

.login-history .el-table {
  margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .personal-center {
    padding: 10px;
  }

  .el-col {
    margin-bottom: 20px;
  }

  .stat-item {
    padding: 15px 0 !important;
  }

  .stat-number {
    font-size: 24px !important;
  }
}
</style>
